<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="固件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入固件名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="固件版本号" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入固件版本号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="创建时间" style="width: 308px">
            <el-date-picker
               v-model="dateRange"
               value-format="YYYY-MM-DD"
               type="daterange"
               range-separator="-"
               start-placeholder="开始日期"
               end-placeholder="结束日期"
            ></el-date-picker>
         </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="creatOTA"
          >创建OTA任务</el-button
        >
      </el-col>
      <el-col :span="10">
        <!-- 定制化展示量产固件 -->
        <div>
          <!-- <span>量产固件: {{ firmwareProd?.name ? firmwareProd?.name + '('+ firmwareProd?.version + ') ' || '暂无 ' : '暂无 '}} </span> -->
          <el-button
            type="primary"
            plain
            size="mini"
            @click="showFirmwareDialog"
            >切换量产固件 {{ firmwareProd?.name ? firmwareProd?.name + ' [ '+ firmwareProd?.version + ' ] ' || '暂无 ' : '暂无 '}}</el-button>
        </div>
      </el-col>
      <!-- <el-col :span="1.5">
            <el-button
               type="success"
               plain
               icon="Edit"
               :disabled="single"
               @click="handleUpdate"
               v-hasPermi="['system:post:edit']"
            >修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="danger"
               plain
               icon="Delete"
               :disabled="multiple"
               @click="handleDelete"
               v-hasPermi="['system:post:remove']"
            >删除</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="warning"
               plain
               icon="Download"
               @click="handleExport"
               v-hasPermi="['system:post:export']"
            >导出</el-button>
         </el-col> -->
      <right-toolbar
        :showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column
        label="序号"
        width="60"
        align="center"
        prop="index"
      >
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="固件编号"
        show-overflow-tooltip
        align="center"
        prop="id"
        sortable
      />
      <el-table-column label="固件名称" align="center" prop="name" />
      <el-table-column label="固件版本号" align="center" prop="version" sortable/>
      <el-table-column label="固件类型" align="center" prop="firmwareType">
        <template #default="scope">
          <dict-tag :options="firmware_type" :value="scope.row.firmwareType" />
        </template>
      </el-table-column>
      <el-table-column label="校验和" align="center" prop="file">
        <template #default="scope">
          {{ scope.row.file?.checksum || '--' }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="原始固件" align="center" prop="raw">
        <template #default="scope">
          <el-tag v-if="scope.row.raw == true" type="primary">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="量产固件" align="center" prop="isprod">
        <template #default="scope">
          <el-tag v-if="scope.row?.isprod==true" type="success">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="date"
        width="180"
        sortable
      />
      <el-table-column label="描述" align="center" prop="desc" width="180" show-overflow-tooltip/>
      <el-table-column
        label="操作"
        width="180"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改固件对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="firmwareRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        @submit.prevent
      >
        <el-form-item label="固件文件">
          <el-upload
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <el-button>
              {{options.file?'重新选择':'选择'}}
              <el-icon class="el-icon--right"><Upload /></el-icon>
            </el-button>
          </el-upload>
          <!-- <button @click="uploadFile" :disabled="!options.file">
            上传文件
          </button> -->
        </el-form-item>
        <el-form-item label="固件校验和" prop="checksum">
          <el-input v-model="form.checksum" placeholder="固件校验和" disabled/>
        </el-form-item>
        <el-form-item label="固件名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入固件名称" :disabled="!form.checksum"/>
        </el-form-item>
        <el-form-item label="固件版本号" prop="version">
          <el-input v-model="form.version" placeholder="请输入固件版本号" :disabled="!form.checksum"/>
        </el-form-item>
        <!-- <el-form-item label="固件路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入固件路径" />
        </el-form-item> -->
        <el-form-item label="原始固件" prop="raw">
          <el-switch v-model="form.raw" @change="rawChange" :disabled="!form.checksum"/>
        </el-form-item>
        <el-form-item label="固件类型" prop="firmwareType">
          <el-select v-model="form.firmwareType" placeholder="请选择固件类型" :disabled="!form.checksum">
            <el-option
              v-for="dict in firmware_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
          <!-- <el-select clearable v-model="form.firmwareType" placeholder="可多选" :multiple-limit="10">
                    <el-option v-for="item in 31" :key="item" :label="item" :value="item" />
                </el-select> -->
          <!-- <el-input v-model="form.firmwareType" placeholder="请输入固件类型" /> -->
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.desc"
            type="textarea"
            placeholder="请输入内容"
            :disabled="!form.checksum"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- OTA任务创建 -->
    <el-dialog :title="title" v-model="openOTA" width="500px" append-to-body>
      <el-form
        ref="OTARef"
        :model="formOTA"
        :rules="formOTA.radio == 1 ? rulesOTA : ''"
        label-width="120px"
        @submit.prevent
      >
      <el-form-item label="固件类型" prop="radio">
        <el-radio-group v-model="formOTA.radio" class="ml-4" @change="resetFirmwareIds">
          <el-radio :label="1" size="middle">手环固件</el-radio>
          <el-radio :label="2" size="middle">网关固件</el-radio>
        </el-radio-group>
      </el-form-item>
        <!-- <el-form-item label="固件名称" prop="firmwareid">
          <el-select
            v-model="formOTA.firmwareid"
            placeholder="请选择固件"
            @change="firmwareChange"
            style="width: 260px"
          >
            <el-option
              v-for="dict in postList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="固件类型" prop="firmwareType">
          <el-select
            v-model="formOTA.firmwareType"
            placeholder="请选择固件类型"
            disabled
            style="width: 260px"
          >
            <el-option
              v-for="dict in firmware_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
          &nbsp;&nbsp;&nbsp;
          <el-checkbox
            v-if="formOTA.firmwareType == 'gw-bin'"
            true-label="1"
            false-label="0"
            v-model="formOTA.full"
            >完整固件</el-checkbox
          >
        </el-form-item> -->
        <el-form-item v-if="formOTA.radio == 1" label="手环固件" prop="firmwareid">
          <el-select v-model="formOTA.firmwareid" placeholder="请选择手环固件" @change="(value) => firmwareChange('wb', value)" style="width: 260px">
            <el-option
              v-for="dict in firmwaresLists.wb"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formOTA.radio == 2" label="网关固件(BIN)" prop="firmwareid">
          <el-select v-model="formOTA.firmwareid" placeholder="请选择bin格式固件" @change="(value) => firmwareChange('bin', value)" style="width: 260px">
            <el-option
              v-for="dict in firmwaresLists.bin"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formOTA.radio == 2" label="网关固件(FS)" prop="firmwareid_1">
          <el-select v-model="formOTA.firmwareid_1" placeholder="请选择fs格式固件" @change="(value) => firmwareChange('fs', value)" style="width: 260px">
            <el-option
              v-for="dict in firmwaresLists.fs"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formOTA.radio == 1" label="路径" prop="path">
          <el-input
            v-model="formOTA.path"
            placeholder="请输入路径"
            style="width: 260px"
          />
        </el-form-item>
        <!-- v-if="
            formOTA.firmwareType === 'gw-bin' ||
            formOTA.firmwareType === 'gw-fs'
          " -->
        <el-form-item
          v-if="formOTA.radio"
          label="网关MAC地址"
          prop="gw_mac"
        >
          <el-select
            clearable
            v-model="formOTA.gw_mac"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入网关"
            :multiple-limit="10"
            style="width: 260px"
            :disabled="formOTA.gw_full === 1"
          >
            <el-option
              v-for="item in gatewayList"
              :key="item.mac"
              :label="item.mac"
              :value="item.mac"
            />
          </el-select>
          <!-- <el-input v-model="formOTA.gw_mac" placeholder="请输入网关" style="width: 260px"/> -->
          &nbsp;&nbsp;&nbsp;
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="formOTA.gw_full"
            @change="gwFullChange($event)"
            :disabled="formOTA.isprod"
            >全部</el-checkbox
          >
        </el-form-item>
        <el-form-item
          v-if="formOTA.radio == 1"
          label="手环MAC地址"
          prop="wb_mac"
        >
          <el-select
            v-model="formOTA.wb_mac"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入手环网关"
            clearable
            :multiple-limit="50"
            style="width: 260px"
            :disabled="formOTA.wb_full === 1"
          >
            <el-option
              v-for="item in wristbandList"
              :key="item.mac"
              :label="item.mac"
              :value="item.mac"
            />
          </el-select>
          <!-- <el-input v-model="formOTA.wb_mac" placeholder="请输入手环网关" style="width: 260px"/> -->
          &nbsp;&nbsp;&nbsp;
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="formOTA.wb_full"
            @change="wbMacChange($event)"
            >全部</el-checkbox
          >
        </el-form-item>
        <!-- <el-form-item label="强制更新" prop="wb_mac">
          <el-switch v-model="formOTA.force" @change="forceChange" />
        </el-form-item>
        <el-form-item label="长期更新" prop="wb_mac">
          <el-switch
            :disabled="!(formOTA.gw_full || formOTA.wb_full)"
            v-model="formOTA.remain"
            @change="remainChange"
          />
        </el-form-item> -->
        <!-- "uponly" | "updown" | "force", -->
        <el-form-item label="升级模式" prop="updateMode">
          <el-radio-group v-model="formOTA.updateMode" class="ml-4">
            <el-radio
              v-for="item in ota_update_mode"
              :key="item.value"
              :label="item.value"
              size="middle"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
          <!-- <el-text type="danger" size="small">开启固件可升级非当前版本，反之只可升级大于当前版本。</el-text> -->
        </el-form-item>
        <el-form-item v-if="formOTA.radio == 1" label="升级限制" prop="updateLimit">
          <el-radio-group v-model="formOTA.updateLimit" class="ml-4">
            <el-radio
              v-for="item in ota_update_limit"
              :key="item.value"
              :label="item.value"
              size="middle"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formOTA.radio == 1&&formOTA.updateLimit==1" label="升级时限" prop="duration">
          <el-input-number
            v-model="formOTA.duration"
            placeholder="请输入手环升级时长限制"
            class="mx-4"
            :min="0"
            :max="86400"
            :step="1"
            step-strictly
            controls-position="right"
            style="width: 260px"
          />
          <span>&nbsp;&nbsp;&nbsp;&nbsp;秒</span>
          <!-- <el-text type="danger" size="small">限制手环升级时长，当到达指定时长则停止升级任务。</el-text> -->
        </el-form-item>
        <el-form-item v-if="formOTA.radio == 1&&formOTA.updateLimit==2" label="升级数量" prop="wb_count">
          <el-input-number
            v-model="formOTA.wb_count"
            placeholder="请输入手环升级数量"
            class="mx-4"
            :min="0"
            :max="10000"
            :step="1"
            step-strictly
            controls-position="right"
            style="width: 260px"
          />
          <el-text type="danger" size="small">限制手环升级数量，当指定数量升完则停止升级任务。</el-text>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormOTA">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 固件列表弹窗 -->
    <el-dialog
      title="选择量产固件"
      v-model="firmwareDialogVisible"
      width="780px"
      append-to-body
    >
      <el-table
        :data="firmwaresLists.wb"
        border
        highlight-current-row
        @row-click="selectFirmware"
      >
        <el-table-column label="固件编号" prop="id" min-width="150" align="center" />
        <el-table-column label="固件名称" prop="name" align="center" />
        <el-table-column label="固件版本号" prop="version" align="center" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="firmwareDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="setProductionFirmware">设置为量产固件</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Firmware">
import {
  listPost,
  addPost,
  delPost,
  getPost,
  updatePost,
} from "@/api/system/post";
import PreviewCode from "@/components/PreviewCode/index.vue";
import {
  uploadFiles,
  createFirmwares,
  getFirmwaresList,
  // getFirmwaresType,
  getFirmwaresById,
  updateFirmwaresById,
  deleteFirmwaresById,
} from "@/api/system/user";
import { getType } from "@/api/system/dict/type";
import { createOTA, getFirmwaresListByType, getFirmwareProdTask, SetFirmwareProdTask } from "@/api/system/firmware/ota";
import { getGatewayList } from "@/api/system/firmware/gateway";
import { getWristbandList } from "@/api/system/firmware/wb";

const showCode = ref(false);

const { proxy } = getCurrentInstance();
const { action_ota, firmware_type, ota_update_mode } = proxy.useDict(
  "action_ota",
  "firmware_type",
  "ota_update_mode"
);
// console.log(firmware_type);

const postList = ref([]);
const firmwaresLists = ref([]);
const firmwareProd = ref([]);
const firmwareDialogVisible = ref(false); // 控制弹窗显示
const selectedFirmware = ref(null); // 选中的固件
const open = ref(false);
const openOTA = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const gatewayList = ref([]);
const wristbandList = ref([]);
const ota_update_limit = ref([
  { label: "不限制", value: 0 },
  { label: "开启时间限制", value: 1 },
  { label: "开启数量限制", value: 2 },
]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    name: undefined,
    status: undefined,
  },
  rules: {
    name: [{ required: true, message: "固件名称不能为空", trigger: "blur" }],
    version: [
      { required: true, message: "固件版本号不能为空", trigger: "blur" },
    ],
    // path: [{ required: true, message: "固件路径不能为空", trigger: "blur" }],
    firmwareType: [
      { required: true, message: "固件类型不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// OTA任务
const dataOTA = reactive({
  formOTA: {},
  queryParamsOTA: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    name: undefined,
    status: undefined,
  },
  rulesOTA: {
    firmwareid: [
      { required: true, message: "固件名称不能为空", trigger: "blur" },
    ],
    path: [{ required: true, message: "路径不能为空", trigger: "blur" }],
    duration: [{ required: true, message: "升级时限不能为空", trigger: "blur" }],
    wb_count: [{ required: true, message: "手环数量不能为空", trigger: "blur" }],
  },
});

const { queryParamsOTA, formOTA, rulesOTA } = toRefs(dataOTA);

const options = reactive({
  file: null, // 上传的固件文件
  filename: "firmware", // 默认文件名称
  outputType: "bin", // 默认输出文件类型（例如 .bin 或 .hex）
  previews: {}, // 预览数据（如果需要）
});

const typeList = reactive([]);
function rawChange(val) {
  if (!val) {
  }
}
// 网关勾选全部
function gwFullChange(event, label) {
  // 清空网关
  formOTA.value.gw_mac = [];
  // 取消勾选全部时，初始长期更新设置 并disabled
  if (event === "0") formOTA.value.remain = false;
}
// 手环网关勾选全部
function wbMacChange(event, label) {
  // 清空手环网关
  formOTA.value.wb_mac = [];
  // 取消勾选全部时，初始长期更新设置 并disabled
  if (event === "0") formOTA.value.remain = false;
}

// 初始化网关和手环的mac数据
function initGatewayWristbandData() {
  // 网关列表
  getGatewayList().then((response) => {
    // console.log('gw',response.data);
    const { data, msg, code } = response;
    gatewayList.value = code === 200 ? data?.data : [];
  });
  // 手环列表
  getWristbandList().then((response) => {
    // console.log('wb',response);
    const { data, msg, code } = response;
    wristbandList.value = code === 200 ? data?.data : [];
  });
}
// 显示固件列表弹窗
function showFirmwareDialog() {
  firmwareDialogVisible.value = true;
}

// 选择固件
function selectFirmware(row) {
  selectedFirmware.value = row;
}
/** 查询量产固件列表 */
function getFProdTask() {
  getFirmwareProdTask().then((response) => {
    console.log('量产固件', response.data);
    firmwareProd.value = response?.data || null;
  });
}
// 设置为量产固件
function setProductionFirmware() {
  if (!selectedFirmware.value) {
    proxy.$modal.msgError("请选择一个固件！");
    return;
  }
  console.log('设置量产固件', selectedFirmware.value,{ id: selectedFirmware.value.id });
  SetFirmwareProdTask({ id: selectedFirmware.value.id }).then((response) => {
    const { code, msg } = response;
    if (code === 200) {
      proxy.$modal.msgSuccess("量产固件设置成功！");
      firmwareDialogVisible.value = false;
      getFProdTask(); // 更新量产固件信息
      getList();
      getFirmwaresLists();
    } else {
      proxy.$modal.msgError(msg || "量产固件设置失败！");
    }
  });
}
/** 查询固件列表 */
function getList() {
  loading.value = true;
  getFirmwaresList(queryParams.value).then((response) => {
    console.log('固件列表', response.data.data);
    postList.value = response.data.data;
    //  postList.value = response.rows;
    total.value = response.data.total;
    loading.value = false;
  });
}

// function getTypeList() {
//   getFirmwaresType().then((response) => {
//     console.log("getTypeList----",response);
//     const { data, msg, code } = response;
//     if (code === 200) {
//       typeList.value = data;
//     } else {
//       typeList.value = [];
//     }
//   });
// }

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    fileid: undefined,
    name: undefined,
    version: undefined,
    raw: false,
    isProd: null,
    desc: undefined,
    path: undefined,
    firmwareType: undefined,
    checksum: undefined
  };
  proxy.resetForm("firmwareRef");
}

// OTA表单重置
function resetOTA() {
  formOTA.value = {
    full: 0,
    path: "/store/firmware/last.bin",
    radio: 1,
    firmwareid: "", // 固件id
    firmwareid_1: "", // 固件fs id
    gw_mac: [], // 网关
    wb_mac: [], // 手环网关
    gw_full: 0,
    wb_full: 0,
    duration: undefined,
    wb_count: undefined,
    updateMode: 'updown',
    updateLimit: 0,
    isprod: null,
  };
  proxy.resetForm("OTARef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加固件";
}

// 创建OTA任务
function creatOTA() {
  resetOTA();
  // 获取网关和手环数据
  initGatewayWristbandData();
  openOTA.value = true;
  title.value = "创建OTA任务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getFirmwaresById(id).then((response) => {
    // console.log(response);
    form.value = response.data;
    open.value = true;
    title.value = "修改固件";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["firmwareRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        // console.log(form.value);
        updateFirmwaresById(form.value).then((response) => {
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("固件修改成功");
            open.value = false;
            getList();
            getFirmwaresLists();
          } else {
            proxy.$modal.msgError("固件修改失败");
          }
        });
      } else {
        // console.log(form.value);
        createFirmwares(form.value).then((response) => {
          // console.log(response);
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("固件新增成功");
            open.value = false;
            getList();
            getFirmwaresLists();
          } else {
            proxy.$modal.msgError("固件新增失败");
          }
        });
      }
    }
  });
}

// 提交OTA任务
function submitFormOTA() {
  proxy.$refs["OTARef"].validate((valid) => {
    if (valid) {
      if(formOTA.value.radio == 2 && (!formOTA.value.firmwareid && !formOTA.value.firmwareid_1)){
        proxy.$modal.msgError("必须选择一个网关固件");
        return
      }
      if(formOTA.value.gw_full != 1&&formOTA.value.gw_mac?.length<=0){
        proxy.$modal.msgError("请选择进行升级的网关！");
        return
      }
      if(formOTA.value.radio == 1 && formOTA.value.wb_full != 1&&formOTA.value.wb_mac?.length<=0){
        proxy.$modal.msgError("请选择要升级的手环！");
        return
      }
      const params = {
        ...formOTA.value,
        gw_mac: formOTA.value.gw_full != 1 && formOTA.value.gw_mac.length >0 ? formOTA.value.gw_mac.join(','):'',
        wb_mac: formOTA.value.wb_full != 1 && formOTA.value.wb_mac.length >0 ? formOTA.value.wb_mac.join(','):'',
      };
      if (formOTA.value.id != undefined) {
        //   console.log(form.value);
        //   updateFirmwaresById(form.value).then((response) => {
        //     const { code, data, msg } = response;
        //     if (code === 200) {
        //       proxy.$modal.msgSuccess("固件修改成功");
        //       openOTA.value = false;
        //       getList();
        //     } else {
        //       proxy.$modal.msgError("固件修改失败");
        //     }
        //   });
      } else {
        // console.log('创建OTA任务', formOTA.value);
        formOTA.value.dictType = "firmware_type";
        // console.log('提交OTA任务',formOTA.value )
        createOTA({
          ...params,
          dictType: formOTA.value.dictType
        }).then((response) => {
          // console.log(response);
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("OTA任务创建成功,请至OTA任务列表查看！");
            openOTA.value = false;
            getList();
          } else {
            proxy.$modal.msgError("OTA任务创建失败");
          }
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + ids + '"的数据项？')
    .then(function () {
      return deleteFirmwaresById(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  /*proxy.download("system/post/export", {
    ...queryParams.value
  }, `post_${new Date().getTime()}.xlsx`);*/
}

// OTA任务选择固件 带出固件类型
function firmwareChange(el,value) {
  const selectedFirmware = firmwaresLists.value[el].find((dict) => dict.id === value);
  console.log('OTA任务选择固件: ', selectedFirmware)
  formOTA.value.isprod = selectedFirmware?.isprod || null;
  // formOTA.value.firmwareType = selectedFirmware.firmwareType; //value.firmwareType
  // formOTA.value.version = selectedFirmware.version;
  formOTA.value.full = 0;
  formOTA.value.gw_mac = [];
  formOTA.value.gw_full = 0;
  formOTA.value.wb_mac = [];
  formOTA.value.wb_full = 0;
  // formOTA.value.force = false;
  // formOTA.value.remain = false;
  form.value.duration = undefined;
  form.value.wb_count = undefined;

  // console.log('OTA任务选择固件', form.value)
}
// 固件列表
function getFirmwaresLists(){
  getFirmwaresListByType().then((response) => {
    // console.log("固件列表",response);
    const { data, msg, code } = response;
    if (code === 200) {
      console.log('firmwaresLists', data)
      firmwaresLists.value = data;
    } else {
      firmwaresLists.value = [];
    }
  });
}
// getTypeList();
getFirmwaresLists();
getList();
getFProdTask();

/** 覆盖默认上传行为 */
function requestUpload() {}

/** 上传预处理 */
function beforeUpload(file) {
  // 定义允许的固件文件格式
  const allowedFirmwareTypes = [".bin", ".hex"];
  const fileExtension = file.name
    .slice(file.name.lastIndexOf("."))
    .toLowerCase();

  // 校验文件格式
  if (!allowedFirmwareTypes.includes(fileExtension)) {
    proxy.$modal.msgError(
      "文件格式错误，请上传固件类型文件，如：.bin 或 .hex 后缀的文件。"
    );
    return false; // 阻止上传
  }

  // 校验文件大小（例如限制为 10MB）
  const maxSize = 10 * 1024 * 1024; // 10MB
  if (file.size > maxSize) {
    proxy.$modal.msgError("文件大小超过限制，请上传小于 10MB 的文件。");
    return false; // 阻止上传
  }
  // 文件格式和大小都符合要求
  options.file = file; // 存储文件对象
  options.filename = file.name; // 存储文件名
  form.value.name = file.name;
  let formData = new FormData();
  formData.append("files", options.file);
  uploadFiles(formData).then((response) => {
    const { code, data, msg } = response;
    if (code === 200) {
      form.value.fileid = data.fileid;
      form.value.name = data.file_name;
      form.value.path = data.file_path;
      form.value.checksum = data.checksum;
      proxy.$modal.msgSuccess("固件上传成功");
    } else {
      proxy.$modal.msgSuccess("固件上传失败");
    }
  });
  return true;
}

/** 上传固件 */
function uploadFile() {
  let formData = new FormData();
  formData.append("files", options.file);
  uploadFiles(formData).then((response) => {
    const { code, data, msg } = response;
    if (code === 200) {
      form.value.fileid = data.fileid;
      form.value.name = data.file_name;
      form.value.path = data.file_path;
      proxy.$modal.msgSuccess("固件上传成功");
    } else {
      proxy.$modal.msgSuccess("固件上传失败");
    }
  });
}
/** 重置固件ID选择 */
function resetFirmwareIds() {
  formOTA.value.firmwareid = undefined
  formOTA.value.firmwareid_1 = undefined
  formOTA.value.updateLimit = 0
  formOTA.value.duration = undefined
  formOTA.value.wb_count = undefined
  formOTA.value.wb_mac = []
  formOTA.value.wb_full = 0
  formOTA.value.gw_mac = []
  formOTA.value.gw_full = 0
  formOTA.value.path = '/store/firmware/last.bin'
  formOTA.value.updateMode = 'updown'
  formOTA.value.remain = false
  formOTA.value.isprod = null
}
</script>
